package com.guanzi.big_data_mq_process.listener;

import com.baomidou.mybatisplus.extension.service.IService;
import com.guanzi.big_data_mq_process.util.SpringContextHolder;

import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.function.Function;
import java.util.function.Predicate;

/**
 * EasyExcel 导入缓存监听器封装
 */
public class EasyExcelCacheListener {

    // BO类和对应导入监听器的Map
    private static final Map<Class<?>, EasyExcelListener<?, ?>> cacheListener = new ConcurrentHashMap<>();

    // 用于导入的线程池 bean名称
    private static final String IMPORT_THREAD_POOL_BEAN_NAME = "importThreadPool";

    private static final int DEFAULT_BATCH_SIZE = 10000;

    public static <PO, BO> EasyExcelListener<PO, BO> getCacheListener(
            Class<BO> boClass,
            Predicate<BO> boPredicate,
            Function<BO, PO> convertFunction,
            IService<PO> poService) {
        return getCacheListener(boClass, boPredicate, convertFunction, poService,
                DEFAULT_BATCH_SIZE);
    }

    public static <PO, BO> EasyExcelListener<PO, BO> getCacheListener(
            Class<BO> boClass, Predicate<BO> boPredicate, Function<BO, PO> convertFunction, IService<PO> poService,
            int batchSize) {
        return getCacheListener(
                boClass, boPredicate, convertFunction, poService, batchSize,
                SpringContextHolder.getBean(IMPORT_THREAD_POOL_BEAN_NAME));
    }

    public static <PO, BO> EasyExcelListener<PO, BO> getCacheListener(
            Class<BO> boClass, Predicate<BO> boPredicate, Function<BO, PO> convertFunction, IService<PO> poService, int batchSize,
            ThreadPoolExecutor threadPoolExecutor) {
        return (EasyExcelListener<PO, BO>) cacheListener.computeIfAbsent(boClass, key -> new EasyExcelListener<>(
                boPredicate,
                convertFunction,
                poService,
                batchSize,
                threadPoolExecutor
        ));
    }

}
